package com.bodystm.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mimosa.util.datetime.DateFormatUtil;
import com.bodystm.bean.Bed;
import com.bodystm.bean.Patient;
import com.bodystm.bean.PatientBedUser;
import com.bodystm.bean.PatientEquip;
import com.bodystm.bean.Temperature;
import com.bodystm.service.BedService;
import com.bodystm.service.PatientBedService;
import com.bodystm.service.PatientEquipService;
import com.bodystm.service.PatientService;
import com.bodystm.service.TemperatureService;
import com.bodystm.system.SystemSetting;
import com.bodystm.system.SystemSettingService;
import com.bodystm.web.DeviceSettings;
import com.bodystm.web.EasyUiMessage;
/**
 * print chart data
 * @author ehl
 *
 */
@Controller
@RequestMapping("/show")
public class ShowController {
	@Resource
	private TemperatureService temperatureService;

	@Resource
	private PatientService patientService;

	@Resource
	private BedService bedService;
	@Resource
	private SystemSettingService systemSettingService;

	@Autowired
	private PatientEquipService patientEquipService;
	
	static final String DATE_PATTERN = "yyyy-MM-dd";
	/**
	 * 鏃ュ織璁板綍
	 */
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping("/index.action")
	public String index(Patient patient, Model model) {
		patient = this.patientService.getEntity(patient.getId());
		model.addAttribute("patient", patient);
		return "show/index";
	}

	@RequestMapping("/print.action")
	public String print(Patient patient) {
		return "show/print";
	}

	static final String LONG_FORMAT_DATE = "yyyy-MM-dd HH:mm:ss";

	@RequestMapping("/newPoint.action")
	@ResponseBody
	public String newPoint(String lastTime, String equipNo) {
		Date lastDate = null;
		if (StringUtils.isNotBlank(lastTime)) {
			lastDate = DateFormatUtil.parseDate(lastTime, LONG_FORMAT_DATE);
		}
		if (lastDate == null) {
			lastDate = new Date();
		}
		Temperature temperature = this.temperatureService.getLatestPoint(lastDate, equipNo);
		String data = "[]";
		if (temperature != null) {
			data = String.format("[\"%s\",%f]", DateFormatUtils.format(temperature.getMeasureTime(), LONG_FORMAT_DATE),
					temperature.getMeasureNum());
		}
		EasyUiMessage message = new EasyUiMessage();
		message.setData(data);
		return message.toString();
	}

	
	
	@RequestMapping("/export.action")
	public String export(Patient queryPatient, Integer distance, Model model) throws ParseException {
		try {
			Patient resultPatient = this.patientService.getEntity(queryPatient.getId());
			// 鑾峰彇搴婁綅淇℃伅
			
			Bed bed = null;//this.bedService.getEntity(resultPatient.getBed().getId()); 2018年1月8日23:24:58
			// 鑾峰彇鏈�繎鍑犲ぉ鐨勬暟鎹�
			if (distance == null || distance < 1) {
				distance = 7;
			}
			//Date maxMeasureDate = this.temperatureService.getLatestDate(resultPatient, distance);			
			//改为获取入院时间，打印从这个时间往后推7天的体温表 by rxz 20160521
			Date maxMeasureDate = resultPatient.getListenStartTime();
			Calendar cal=Calendar.getInstance();
			cal.setTime(maxMeasureDate);
			cal.add(Calendar.DAY_OF_YEAR, distance-1);
			maxMeasureDate=cal.getTime();
			List<Object> tiwenResultList = null;
			if (maxMeasureDate != null) {
				//续贴功能相关
				List<Object> temperaturesTEmp=null;

				List<PatientEquip> lstPE2=null;
				lstPE2=patientEquipService.getPatientEquipByPatient(resultPatient.getId());
				if(lstPE2!=null){
					tiwenResultList=new ArrayList<Object>();
					String strMacs="";
					for(int j=0;j<lstPE2.size();j++){
						strMacs+="'"+lstPE2.get(j).getEquipNo()+"',";
					}
					if(strMacs.length()>0){
						strMacs=strMacs.substring(0,strMacs.length()-1);
						tiwenResultList = this.temperatureService.getLatestRecordByMacs(resultPatient, maxMeasureDate, distance,strMacs);
					}
						
				}
//				tiwenResultList = this.temperatureService.getLatestRecord(resultPatient, maxMeasureDate, distance);
			} else {
				tiwenResultList = Collections.emptyList();
				maxMeasureDate = new Date();
			}
			// 璁＄畻浣忛櫌澶╂暟
			int daysIn = (int) ((maxMeasureDate.getTime() - resultPatient.getStartTime().getTime())
					/ DateUtils.MILLIS_PER_DAY);
			// 璁＄畻浣撴俯鐐逛俊鎭�
			long startTime = resultPatient.getStartTime().getTime();//maxMeasureDate.getTime() - distance * DateUtils.MILLIS_PER_DAY;
			Date date = null;
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dateStr = null;
			Map<String, Integer> dateList = new LinkedHashMap<String, Integer>(distance);
			for (int i = 0; i < distance; i++) {
				if(i>0)
				startTime = startTime + DateUtils.MILLIS_PER_DAY;
				date = new Date(startTime);
				dateStr = dateFormat.format(date);

				dateList.put(dateStr, i);
			}

			Object[] values = null;
			int[] resultTemperature=new int[6*distance];
			//byte[][] resultArray = new byte[distance * 6][8 * 5];// distance*5
			String hour = null;
			int xIndex = 0, yIndex = 0;
			DateFormat hourFormat = new SimpleDateFormat("HH");
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			float tempTemp=0;
			boolean iffirst=true;
			for (Object obj : tiwenResultList) {
				values = (Object[]) obj;
				
				// by rxz 20160219
				calendar.setTime(sdf.parse(values[1].toString()));
				//去掉首个低温数据 by rxz 20160521
				if(iffirst){
					iffirst=false;
					if(calendar.get(Calendar.HOUR_OF_DAY) % 2==0){
						continue;
					}
				}
				if (calendar.get(Calendar.HOUR_OF_DAY) % 2 != 0)
					continue;
				
				// by rxz 20160219
				logger.info("tiwen : {}, date : {}", values);
				dateStr = dateFormat.format(values[1]);
				if(dateList.get(dateStr)==null)continue;
				xIndex = dateList.get(dateStr) * 6;
				hour = hourFormat.format(values[1]);
				switch (hour) {
				case "02":
					break;
				case "06":
					xIndex += 1;
					break;
				case "10":
					xIndex += 2;
					break;
				case "14":
					xIndex += 3;
					break;
				case "18":
					xIndex += 4;
					break;
				case "22":
					xIndex += 5;
					break;
				default:
					xIndex = -1;
				}
				if (xIndex < 0) {
					continue;
				}
				yIndex = (int) ((42.6 - (Float) values[0]) / 0.2);
				//resultArray[xIndex][yIndex] = 1;
				tempTemp=(Float) values[0];
				tempTemp=tempTemp>34?tempTemp:34;
				/*if((int) (((Float) values[0]-34)/0.01)==0){
					resultTemperature[xIndex]=-1;
				}else{
					resultTemperature[xIndex]=(int) (((Float) values[0]-34)/0.01);
				}*/
				if((int) ((tempTemp-34)/0.01)==0){
					resultTemperature[xIndex]=-1;
				}else{
					resultTemperature[xIndex]=(int) ((tempTemp-34)/0.01);
				}
				
			}
			SystemSetting systemSetting = systemSettingService.getSystemSetting();
			if (systemSetting!=null&&StringUtils.isNotBlank(systemSetting.getHospitalName())) {
				model.addAttribute("hospitalName", systemSetting.getHospitalName());
			}
			model.addAttribute("daysIn", daysIn);
			model.addAttribute("distance", distance);
			model.addAttribute("patient", resultPatient);
			model.addAttribute("bed", bed);
			model.addAttribute("resultDateList", dateList.keySet());
			//model.addAttribute("resultArray", resultArray);
			model.addAttribute("resultTemperature", resultTemperature);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "show/export";
	}

	@RequestMapping("/query.action")
	@ResponseBody
	public String query(Patient patient, String startTimeStr, String endTimeStr, Integer rows) {
		Date startTime = null;
		if (StringUtils.isNotBlank(startTimeStr)) {
			startTime = DateFormatUtil.parseDate(startTimeStr, DATE_PATTERN);
		}
		Date endTime = null;
		if (StringUtils.isNotBlank(endTimeStr)) {
			endTime = DateFormatUtil.parseDate(endTimeStr, DATE_PATTERN);
		}
		List<Temperature> resultList = this.temperatureService.query(patient.getEquipNo(), startTime, endTime, rows);
		StringBuilder builder = new StringBuilder("[");
		for (Temperature temp : resultList) {
			builder.append("{\"").append(DateFormatUtils.format(temp.getMeasureTime(), "yyyy-MM-dd HH:mm:ss"));
			builder.append("\":").append(temp.getMeasureNum()).append("},");
		}
		// Date date = new Date();
		// for (int i = 0; i < 20; i++) {
		// builder.append("{\"").append(
		// DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
		// builder.append("\":").append(RandomUtils.nextFloat(36, 38))
		// .append("},");
		// }
		if (builder.length() > 1) {
			builder.deleteCharAt(builder.length() - 1);
		}
		builder.append("]");
		EasyUiMessage message = new EasyUiMessage();
		message.setData(builder.toString());
		return message.toString();
	}
}